package com.zjw.utils;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zjw.system.SystemConstant;

import java.util.Calendar;
import java.util.Date;

public class JWTUtil {

    public static void main(String[] args) {

        System.out.println(creatJWT("123"));
        System.out.println(validateJWT("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEyMyIsImV4cCI6MTcwMzkzNjA4OX0.O2uTAlSlab-l967VUcDL2GCfYk_ZL7ehKYdXdUW0yng"));
        System.out.println(validateJWT("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEyeyIsImV4cCI6MTcwMzkzNjA4OX0.O2uTAlSlab-l967VUcDL2GCfYk_ZL7ehKYdXdUW0yng"));
        System.out.println(validateJWT("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjciLCJleHAiOjE3MDM5MzgwMzZ9._mCAfG8ZIoHQl29ttFwmPfKPyJaIgWhz1IbRryCRibc"));
    }


    /**
     * 生成jwt
     *
     * @param id        id
     * @return {@link String}
     */
    public static String creatJWT(String id) {
        JWTCreator.Builder builder = JWT.create();
//        设置载荷中的内容
        builder.withClaim("id", id);

//        设置过期时间为n小时
//        方法1.
//        Calendar endTime = Calendar.getInstance();
//        endTime.add(Calendar.HOUR, SystemConstant.JWT_EFFECTIVE_DURATION_HOUR);
//        builder.withExpiresAt(endTime.getTime());
//        方法2. 使用工具类
        builder.withExpiresAt(DateUtil.offsetHour(new Date(), SystemConstant.JWT_EFFECTIVE_DURATION_HOUR));

        String JWT = builder.sign(Algorithm.HMAC256(SystemConstant.JWT_SECRET_KEY)).toString();
        return JWT;
    }


    /**
     * 验证jwt
     *
     * @param jwt jwt
     * @return {@link Boolean}
     */
    public static Boolean validateJWT(String jwt){
        if (StrUtil.isBlank(jwt)) {
            return false;
        }
        try {
            JWT.require(Algorithm.HMAC256(SystemConstant.JWT_SECRET_KEY)).build().verify(jwt);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取jwt中的id
     *
     * @param jwt jwt
     * @return {@link Long}
     */
    public static Long getJWTId(String jwt){
        if(!validateJWT(jwt)){
            return -1L;
        }
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SystemConstant.JWT_SECRET_KEY)).build().verify(jwt);
        System.out.println("*-----*");
        System.out.println(verify.getClaim("id").asString());
        Long id = Long.parseLong(verify.getClaim("id").asString());
        System.out.println(id);
        return id;
    }
}
